import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router";
import HomeView from "../views/HomeView.vue";

const routes: Array<RouteRecordRaw> = [
  // 首页
  {
    path: "/",
    name: "/index",
    component: () =>
      import(/* webpackChunkName: "about" */ "../layout/index.vue"),
    redirect: "/users",
    children: [
      // 用户列表
      {
        path: "users",
        name: "用户列表",
        component: () =>
          import(/* webpackChunkName: "about" */ "../views/users.vue"),
      },
      // 角色列表
      {
        path: "roles",
        name: "角色列表",
        component: () =>
          import(/* webpackChunkName: "about" */ "../views/roles.vue"),
      },
      // 权限列表
      {
        path: "rights",
        name: "权限列表",
        component: () =>
          import(/* webpackChunkName: "about" */ "../views/rights.vue"),
      },
      // 商品列表
      {
        path: "goods",
        name: "商品列表",
        component: () =>
          import(/* webpackChunkName: "about" */ "../views/goods.vue"),
      },
      // 分类参数
      {
        path: "params",
        name: "分类参数",
        component: () =>
          import(/* webpackChunkName: "about" */ "../views/params.vue"),
      },
      // 商品分类
      {
        path: "categories",
        name: "商品分类",
        component: () =>
          import(/* webpackChunkName: "about" */ "../views/categories.vue"),
      },
      // 订单列表
      {
        path: "orders",
        name: "订单列表",
        component: () =>
          import(/* webpackChunkName: "about" */ "../views/orders.vue"),
      },
      // 数据报表
      {
        path: "reports",
        name: "数据报表",
        component: () =>
          import(/* webpackChunkName: "about" */ "../views/reports.vue"),
      },
    ],
    meta: {
      auth: true,
    },
  },
  {
    path: "/login",
    name: "Login",
    component: () =>
      import(/* webpackChunkName: "about" */ "../views/Login.vue"),
  },
];

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes,
});

// 导航守卫
// 所有路由跳转之前都会经过这个函数，你可以在这个函数内部判断能否访问这个路由。起到路由拦截的作用。
router.beforeEach((to, from, next) => {
  // console.log(to);
  // console.log(from);
  if (to.meta.auth) {
    const token = localStorage.getItem("token") || undefined;
    if (token) next();
    else next(`/login?redirect=${to.path}`);
  } else {
    next();
  }
});

export default router;
